import { Select, Input, message } from 'antd'
import React, { useState, useEffect, useRef, useImperativeHandle } from 'react'
import { v4 as uuidv4 } from 'uuid'
import DynamicTable from '@/components/dynamic-table/index.jsx'
import ConfigAdd from '../config-add/index.jsx'
import {
  omnibusPageList,
  omnibusBatchSave,
  omnibusDelete,
  templatePageList,
} from '@/api/base-config.js'

const ConfigList = React.forwardRef((props, ref) => {
  const { typeCode } = props.config
  const configAddRef = useRef()
  const [templateOptions, setTemplateOptions] = useState([])

  const requestTemplateOptions = () => {
    templatePageList({ projectId: props.projectId, templateType: typeCode, pageSize: 10000 }).then(
      (res) => {
        const { data } = res
        let list = data.pageInfo.list

        setTemplateOptions(
          list.map((item) => {
            return {
              value: item.templateCode,
              label: item.templateName,
            }
          })
        )
      }
    )
  }

  const [loading, setLoading] = useState(false)
  const [data, setData] = useState([])
  const initRow = () => {
    return {
      key: uuidv4(),
      projectId: props.projectId,
      tempalteId: '',
      templateName: '',
      configCode: '',
      configName: '',
      configType: typeCode,
    }
  }

  const requestTableData = () => {
    setLoading(true)
    omnibusPageList({
      configType: typeCode,
    }).then((res) => {
      const { data } = res
      let list = data.pageInfo.list
      list.forEach(item => {
        item.key = uuidv4()
      })
      if (list.length == 0) {
        list.push(initRow())
      }
      setData(list)
      setLoading(false)
    })
  }

  const setFieldData = (index, field, value) => {
    data[index][field] = value

    if (field == 'tempalteId') {
      data[index].templateName = templateOptions.find(
        (item) => item.value == value
      ).label
    }

    setData([...data])
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (text, record, index) => {
        return index + 1
      },
    },
    {
      title: '模版',
      dataIndex: 'tempalteId',
      key: 'tempalteId',
      render: (text, record, index) => {
        return (
          <Select
            options={templateOptions}
            value={text}
            onChange={(value) => {
              setFieldData(index, 'tempalteId', value)
            }}
            placeholder="请选择模版"
            style={{ width: '100%' }}
          ></Select>
        )
      },
    },
    {
      title: '配置编码',
      dataIndex: 'configCode',
      key: 'configCode',
      render: (text, record, index) => {
        return (
          <Input
            value={text}
            onChange={(e) => {
              setFieldData(index, 'configCode', e.target.value)
            }}
            placeholder="请输入配置编码"
            autoComplete='off'
          />
        )
      },
    },
    {
      title: '配置名称',
      dataIndex: 'configName',
      key: 'configName',
      render: (text, record, index) => {
        return (
          <Input
            value={text}
            onChange={(e) => {
              setFieldData(index, 'configName', e.target.value)
            }}
            placeholder="请输入配置名称"
            autoComplete='off'
          />
        )
      },
    },
  ]

  const updateValue = (data) => {
    let tempData = [...data]
    setData(tempData)
  }

  const onView = () => {
    configAddRef.current.open()
  }

  const onSave = () => {
    const saveData = data.map((item, index) => {
      item.sortNum = index + 1
      return item
    })
    omnibusBatchSave({
      configType: typeCode,
      orders: saveData
    }).then(() => {
      message.success('保存成功')
    })
  }

  const onDelete = (index, deleteItem) => {
    if (deleteItem.id) {
      omnibusDelete({ id: deleteItem.id, isConfirm: true }).then(() => {
        message.success('删除成功')
        updateValue(data.filter((item) => item.id !== deleteItem.id))
      })
    }
  }

  const onRefresh = () => {
    requestTemplateOptions()
  }

  useEffect(() => {
    requestTemplateOptions()
    requestTableData()
  }, [])

  useImperativeHandle(
    ref,
    () => ({
      view() {
        onView()
      },
      save()  {
        onSave()
      },
    }),
    [data, onSave, onView]
  )

  const containerRef = useRef()

  const [otherTableProps, setOtherTableProps] = useState({})

  useEffect(() => {
    if (containerRef.current) {
      let y = containerRef.current.clientHeight - 50
      y = data.length * 48 < y ? false : y
      setOtherTableProps({scroll: y ? { y } : null})
    }
  }, [containerRef, data])

  return (
    <div ref={containerRef} style={{height: '100%'}}>
      <DynamicTable
        loading={loading}
        data={data}
        columns={columns}
        initRow={initRow}
        onChange={updateValue}
        onDelete={onDelete}
        isMove={true}
        isFirst={true}
        tableProps={otherTableProps}
      />
      <ConfigAdd
        ref={configAddRef}
        projectId={props.projectId}
        config={props.config}
        show-add={false}
        onRefresh={onRefresh}
        tableCom={props.tableCom}
      />
    </div>
  )
})

ConfigList.displayName = 'ConfigList'

export default ConfigList
